module.exports = class extends think.Model {
  /// 注册用户
  async register (data) {
    const db = think.mongoose('mongo/users')
    console.log(data.phone)
    /// 1.验证手机号是否已存在
    let phoneUser = await db.findOne({phone: data.phone})
    console.log(phoneUser)
    if (phoneUser) return '手机号已存在请前往登录';
    /// 2.两次密码是否一致
    if (data.password != data.password2) return '两次密码输入不一致';
    /// 3.验证PID是否存在
    let pid = ''
    try {
      let _pid = think.objId(data.pid)
      let piduser = await db.findOne({_id: _pid})
      if (!piduser) pid = '邀请码不存在';
    } catch (e) {
      pid = '邀请码错误';
    }
    if (data.pid && pid) return pid;
    /// 4.写入数据库
    data.nickname = data.nickname || data.phone
    data.password = think.encodePwd(data.password)
    let doc = new db(data)
    let user = await doc.save()
    return user
  }
  /// 登录用户
  async login (data) {
    const db = think.mongoose('mongo/users')
    /// 1.验证用户是否已存在
    let user = await db.findOne({phone: data.phone})
    if (!user) return '手机号不存在，请前往注册';
    /// 2.判断密码是否一致
    if (!think.comparPwd(data.password, user.password)) {
      return '密码错误';
    }
    return user
  }
  /// 获取用户信息
  async info (id) {
    const db = think.mongoose('mongo/users')
    let _id = think.objId(id)
    let user = await db.findOne({_id})
    return user
  }
  /// 获取用户信息
  async phone (phone) {
    const db = think.mongoose('mongo/users')
    let user = await db.findOne({phone})
    return user
  }
  /// 修改用户信息
  async edit (data) {
    const db = think.mongoose('mongo/users')
    let _id = think.objId(data._id)
    let user = await db.updateOne({_id}, data)
    return user
  }
  /// 修改用户信息
  async sub (pid) {
    const db = think.mongoose('mongo/users')
    let list = await db.find({pid})
    return list
  }
};
